package net.pingfang.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件读取工具类
 */
@Slf4j
public class FileUtil {

    /**
     * 读取文件内容，作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流  
        FileInputStream fis = new FileInputStream(filePath);
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数  
        int hasRead = 0;
        while ((hasRead = fis.read(bbuf)) > 0) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }

    public static void createDir(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 压缩文件
     *
     * @param filePaths 需要压缩的文件路径集合
     * @throws IOException
     */
    public static void zipFile(List<String> filePaths, ZipOutputStream zos) {
        //设置读取数据缓存大小
        byte[] buffer = new byte[4096];
        try {
            //循环读取文件路径集合，获取每一个文件的路径
            for (String filePath : filePaths) {
                File inputFile = new File(filePath);
                compress(inputFile, zos, "");
            }
        } catch (Exception e) {
            log.info("压缩文件异常 e = {}", ExceptionUtil.getStackTrace(e));
        } finally {
            if (null != zos) {
                try {
                    zos.close();
                } catch (IOException e) {
                    log.info("压缩文件异常 e = {}", ExceptionUtil.getStackTrace(e));
                }
            }
        }
    }

    private static void compress(File file, ZipOutputStream out, String basedir) {
        /* 判断是目录还是文件 */
        if (file.isDirectory()) {
            log.info("压缩：" + basedir + file.getName());
            compressDirectory(file, out, basedir);
        } else {
            log.info("压缩：" + basedir + file.getName());
            compressFile(file, out, basedir);
        }
    }

    /**
     * 压缩一个目录
     */
    private static void compressDirectory(File dir, ZipOutputStream out, String basedir) {
        if (!dir.exists())
            return;

        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            /* 递归 */
            compress(files[i], out, basedir + dir.getName() + "/");
        }
    }

    /**
     * 压缩一个文件
     */
    private static void compressFile(File file, ZipOutputStream out, String basedir) {
        if (!file.exists()) {
            log.info("文件不存在" + file.getAbsolutePath());
            return;
        }
        try {
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));
            String name = file.getName();
            if (!StringUtils.isEmpty(name) && name.contains(".jpg")) {
                name = name.split("&")[0] + ".jpg";
            }
            ZipEntry entry = new ZipEntry(basedir + name);
            out.putNextEntry(entry);
            int count;
            byte data[] = new byte[4096];
            while ((count = bis.read(data, 0, 4096)) != -1) {
                out.write(data, 0, count);
            }
            bis.close();
        } catch (Exception e) {
            log.error("文件压缩异常 e = {}", e);
        }
    }

    // 以字节数组形式读取文件
    public static byte[] readFileToBytes(String filePath) {
        try {
            log.info("filePath:{}", filePath);
            Path path = Paths.get(filePath);
            return Files.readAllBytes(path);
        } catch (IOException e) {
            log.error("readFileToBytes error:{}", e.getMessage());
        }
        return null;
    }

    // 将文件转换成Base64编码的字符串
    public static String readFileToBase64String(String filePath) {
        byte[] bytes = readFileToBytes(filePath);
        return Base64.getEncoder().encodeToString(bytes);
    }

    // 将Base64编码的字符串转换成字节数组
    public static byte[] base64StringToByteArray(String base64String) {
        return base64String==null?null:Base64.getDecoder().decode(base64String);
    }

    // 将Base64编码的字符串转换成字节数组
    public static String byteArrayToBase64String(byte[] bytes) {
        return bytes==null?null:Base64.getEncoder().encodeToString(bytes);
    }

    // 将字节数组写入文件
    public static void writeBytesToFile(byte[] bytes, String filePath) throws IOException {
        Files.write(Paths.get(filePath), bytes);
    }

    // 将Base64编码的字符串写入文件
    public static void writeBase64StringToFile(String base64String, String filePath) throws IOException {
        byte[] bytes = Base64.getDecoder().decode(base64String);
        writeBytesToFile(bytes, filePath);
    }

    // 将文件转换成字节数组
    public static byte[] fileToByteArray(File file) throws IOException {
        byte[] bytes = new byte[(int) file.length()];
        try (FileInputStream fis = new FileInputStream(file)) {
            fis.read(bytes);
        }
        return bytes;
    }

    // 将字节数组转换成文件
    public static void byteArrayToFile(byte[] bytes, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.getParentFile().mkdirs();
                file.createNewFile();
            } catch (IOException e) {
            }
        }
        try (FileOutputStream outputStream = new FileOutputStream(file);
        ) {
            outputStream.write(bytes);
        } catch (IOException e) {
            log.error("byteArrayToFile error:{}", e.getMessage());
        }
    }

}
